<template>
  <div>
    <h1>商品列表</h1>
    <!-- 条件搜索 -->
    <div style="margin-top: 10px">
      <el-form :inline="true" :model="searchForm" class="demo-form-inline">
        <el-form-item label="关键字">
          <el-input
            v-model="searchForm.keyWord"
            placeholder="请输入商品ID/商品名称/商品SPU/品牌名称"
            clearable
          />
        </el-form-item>
        <el-form-item label="商品状态">
          <el-select
            v-model="searchForm.statusId"
            placeholder="请选择商品状态"
            clearable
          >
            <el-option label="草稿" :value="0" />
            <el-option label="待审核" :value="1" />
            <el-option label="已上线" :value="2" />
            <el-option label="已下线" :value="3" />
            <el-option label="缺货" :value="4" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="loadProdList">查询</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div style="margin-top: 10px">
      <el-button type="primary" @click="onAddProd">添加商品</el-button>
      <el-button type="danger" @click="onDeleteBatch">批量删除</el-button>
      <el-button type="info" @click="toProdInfo">商品信息</el-button>
    </div>
    <!-- 表格数据 -->
    <div style="margin-top: 10px">
      <div style="margin-top: 10px">
        <el-table
          :data="tableData"
          stripe
          style="width: 100%"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="30" />
          <el-table-column prop="prodId" label="ID" width="40" />
          <el-table-column prop="prodSpu" label="SPU" width="60" />
          <el-table-column prop="kindName" label="种类" width="80" />
          <el-table-column prop="typeName" label="分类" width="80" />
          <el-table-column prop="prodName" label="名称" width="100" />
          <el-table-column prop="brandName" label="品牌" width="80" />
          <el-table-column prop="unitName" label="单位" width="60" />
          <el-table-column prop="tagName" label="标签" width="80" />
          <el-table-column prop="appr" label="供应商" width="80" />
          <el-table-column prop="prodStatus" label="状态" width="80">
            <template #default="scope">
              <span v-if="scope.row.prodStatus == 0">草稿</span>
              <span v-if="scope.row.prodStatus == 1">待审核</span>
              <span v-if="scope.row.prodStatus == 2">已上线</span>
              <span v-if="scope.row.prodStatus == 3">已下线</span>
              <span v-if="scope.row.prodStatus == 4">缺货</span>
            </template>
          </el-table-column>
          <el-table-column prop="prodImage" label="封面" width="80">
            <template #default="scope">
              <el-image
                v-if="scope.row.prodImage != null"
                :src="scope.row.prodImage"
                style="width: 50px; height: 50px"
              />
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" width="160" />
          <el-table-column label="操作">
            <template #default="scope">
              <el-button type="primary" size="small">商品</el-button>
              <el-button
                type="primary"
                size="small"
                @click="onAddAtta(scope.row)"
                >商品附件</el-button
              >
              <el-button
                type="danger"
                size="small"
                @click="onDeleteProd(scope.row)"
                >删除</el-button
              >
              <el-button
                type="success"
                size="small"
                @click="onBuyProd(scope.row)"
                >购买</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <!-- 分页 -->
    <div style="margin-top: 10px">
      <div class="demo-pagination-block">
        <el-pagination
          v-model:current-page="searchForm.pageNum"
          v-model:page-size="searchForm.pageSize"
          :page-sizes="[2, 4, 6, 8]"
          :background="true"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    <!-- 添加商品---对话框 -->
    <div>
      <el-dialog v-model="dialogFormVisible" title="添加商品" width="500">
        <el-form :model="form" ref="ruleFormRef" :rules="rules">
          <el-form-item
            label="商品种类"
            prop="prodKind"
            :label-width="formLabelWidth"
          >
            <el-radio-group v-model="form.prodKind">
              <el-radio
                v-for="item in kindList"
                :key="item.dictId"
                :value="item.dictValue"
                >{{ item.dictName }}</el-radio
              >
            </el-radio-group>
          </el-form-item>
          <el-form-item
            label="商品类别"
            prop="prodType"
            :label-width="formLabelWidth"
          >
            <el-tree-select
              v-model="form.prodType"
              :data="typeList"
              :render-after-expand="false"
              style="width: 240px"
            />
          </el-form-item>
          <el-form-item
            label="商品名称"
            prop="prodName"
            :label-width="formLabelWidth"
          >
            <el-input v-model="form.prodName" />
          </el-form-item>
          <el-form-item
            label="商品SPU"
            prop="prodSpu"
            :label-width="formLabelWidth"
          >
            <el-input v-model="form.prodSpu" />
          </el-form-item>
          <el-form-item
            label="商品品牌"
            prop="brandId"
            :label-width="formLabelWidth"
          >
            <el-select v-model="form.brandId">
              <el-option
                v-for="item in brandList"
                :label="item.brandName"
                :value="item.brandId"
                :key="item.brandId"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            label="商品单位"
            prop="unitId"
            :label-width="formLabelWidth"
          >
            <el-select v-model="form.unitId">
              <el-option
                v-for="item in unitList"
                :key="item.dictId"
                :value="item.dictValue"
                :label="item.dictName"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            label="商品标签"
            prop="tagId"
            :label-width="formLabelWidth"
          >
            <el-select v-model="form.tagId">
              <el-option
                v-for="item in tagList"
                :key="item.dictId"
                :value="item.dictValue"
                :label="item.dictName"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            label="供应商"
            prop="appr"
            :label-width="formLabelWidth"
          >
            <el-input v-model="form.appr" />
          </el-form-item>
          <el-form-item
            label="商品缩略图"
            prop="prodImage"
            :label-width="formLabelWidth"
          >
            <el-upload
              class="avatar-uploader"
              action="http://localhost:10010/prod/type/uploadImage"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :headers="headers"
            >
              <img v-if="imageUrl" :src="imageUrl" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer" :label-width="formLabelWidth">
            <el-button type="primary" @click="submitForm(ruleFormRef)">
              提交
            </el-button>
            <el-button @click="resetForm(ruleFormRef)">取消</el-button>
          </div>
        </template>
      </el-dialog>
    </div>
    <!-- 添加商品附件---对话框 -->
    <div>
      <el-dialog v-model="attaFormVisible" title="添加商品附件" width="500">
        <el-form :model="form" ref="ruleFormRef" :rules="rules">
          <el-form-item
            label="商品轮播图"
            prop="attaImages"
            :label-width="formLabelWidth"
          >
            <el-upload
              v-model:file-list="fileList"
              action="http://localhost:10010/prod/type/uploadImage"
              list-type="picture-card"
              :on-preview="handlePictureCardPreview"
              :on-remove="handleRemove"
              :headers="headers"
            >
              <el-icon><Plus /></el-icon>
            </el-upload>

            <el-dialog v-model="dialogVisible">
              <img w-full :src="attaImageUrl" alt="Preview Image" />
            </el-dialog>
          </el-form-item>
          <el-form-item label="商品视频" :label-width="formLabelWidth">
            <el-upload
              v-model:file-list="fileViewList"
              class="upload-demo"
              action="http://localhost:10010/prod/type/uploadImage"
              :on-change="handleChange"
              :headers="headers"
            >
              <el-button type="primary">选择文件</el-button>
              <template #tip>
                <div class="el-upload__tip">文件大小不能超过2MB</div>
              </template>
            </el-upload>
          </el-form-item>
          <el-form-item
            label="上架时间"
            prop="upFlag"
            :label-width="formLabelWidth"
          >
            <el-radio-group v-model="attaForm.upFlag">
              <el-radio :value="0">立即上架</el-radio>
              <el-radio :value="1">定时上架</el-radio>
            </el-radio-group>
            <div>
              <div>
                <el-date-picker
                  v-if="attaForm.upFlag == 1"
                  v-model="attaForm.upTime"
                  type="datetime"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  placeholder="请选择上架时间"
                />
              </div>
            </div>
          </el-form-item>
          <el-form-item label="定时下架" :label-width="formLabelWidth">
            <el-switch
              v-model="attaForm.downFlag"
              active-value="1"
              inactive-value="0"
            />
          </el-form-item>
          <el-form-item :label-width="formLabelWidth">
            <div>
              <el-date-picker
                v-if="attaForm.downFlag == 1"
                v-model="attaForm.downTime"
                type="datetime"
                value-format="YYYY-MM-DD HH:mm:ss"
                placeholder="请选择下架时间"
              />
            </div>
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer" :label-width="formLabelWidth">
            <el-button type="primary" @click="submitAttaForm(ruleFormRef)">
              提交
            </el-button>
            <el-button @click="resetAttaForm(ruleFormRef)">取消</el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref, resolveDirective } from "vue";
import {
  getProdList,
  deleteBatch,
  deleteProd,
  getTypeInfo,
  getDictList,
  getBrandList,
  addProd,
  addProdAtta,
} from "../api/api";
import { ElMessage, ElMessageBox } from "element-plus";
import type { FormInstance, FormRules } from "element-plus";
import { Plus } from "@element-plus/icons-vue";
import type { UploadProps } from "element-plus";
import type { UploadUserFile } from "element-plus";
import { useRouter } from "vue-router";

const router = useRouter();

const tableData = ref([]);
const total = ref(0);
const searchForm = ref({
  keyWord: "",
  pageNum: 1,
  pageSize: 2,
  statusId: null,
});

//添加商品form表单
const dialogFormVisible = ref(false);
const formLabelWidth = "140px";
const ruleFormRef = ref<FormInstance>();
const form = ref({
  appr: "",
  brandId: null,
  prodImage: "",
  prodKind: null,
  prodName: "",
  prodSpu: "",
  prodStatus: null,
  prodType: null,
  tagId: null,
  unitId: null,
});

const typeList = ref([]);
const kindList = ref([]);
const brandList = ref([]);
const unitList = ref([]);
const tagList = ref([]);

//添加商品附件form表单
const attaFormVisible = ref(false);
const attaForm = ref({
  attaImages: "",
  attaVideo: "",
  downFlag: null,
  downTime: null,
  prodId: null,
  upFlag: null,
  upTime: null,
});

//跳转商品信息列表页面
const toProdInfo = () => {
  router.push("/home/prodInfo");
};

//上传图片
const imageUrl = ref("");
const headers = ref({
  token: sessionStorage.getItem("token"),
});
const handleAvatarSuccess: UploadProps["onSuccess"] = (
  response,
  uploadFile
) => {
  // imageUrl.value = URL.createObjectURL(uploadFile.raw!)
  imageUrl.value = response.data;
};

//校验
const checkImage = (rule: any, value: any, callback: any) => {
  if (imageUrl.value == null || imageUrl.value == "") {
    return callback(new Error("请上传图片"));
  } else {
    callback();
  }
};
//校验多图片
const checkImages = (rule: any, value: any, callback: any) => {
  if (fileList.value.length == 0) {
    return callback(new Error("请上传图片"));
  } else {
    callback();
  }
};
const rules = reactive<FormRules<any>>({
  prodKind: [
    {
      required: true,
      message: "请选择商品种类",
      trigger: "change",
    },
  ],
  prodType: [
    {
      required: true,
      message: "请选择商品分类",
      trigger: "change",
    },
  ],
  prodName: [{ required: true, message: "请输入商品名称", trigger: "blur" }],
  prodSpu: [
    { required: true, message: "请输入商品SPU", trigger: "blur" },
    { min: 4, max: 4, message: "商品SPU为四位", trigger: "blur" },
  ],
  brandId: [
    {
      required: true,
      message: "请选择商品品牌",
      trigger: "change",
    },
  ],
  unitId: [
    {
      required: true,
      message: "请选择商品单位",
      trigger: "change",
    },
  ],
  tagId: [
    {
      required: true,
      message: "请选择商品标签",
      trigger: "change",
    },
  ],
  appr: [{ required: true, message: "请输入供应商", trigger: "blur" }],
  prodImage: [{ required: true, validator: checkImage, trigger: "blur" }],
  attaImages: [{ required: true, validator: checkImages, trigger: "blur" }],
});
//确认添加商品
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log("submit!");
      form.value.prodImage = imageUrl.value;
      addProd(form.value).then((res) => {
        if (res.data.code == 200) {
          ElMessage.success("添加成功");
          loadProdList();
          dialogFormVisible.value = false;
        } else {
          ElMessage.error(res.data.msg);
        }
      });
    } else {
      console.log("error submit!", fields);
    }
  });
};
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
  dialogFormVisible.value = false;
  form.value = {
    appr: "",
    brandId: null,
    prodImage: "",
    prodKind: null,
    prodName: "",
    prodSpu: "",
    prodStatus: null,
    prodType: null,
    tagId: null,
    unitId: null,
  };

  imageUrl.value = "";
};
//显示添加商品对话框
const onAddProd = () => {
  console.log("onAddProd");
  dialogFormVisible.value = true;
  form.value = {
    appr: "",
    brandId: null,
    prodImage: "",
    prodKind: null,
    prodName: "",
    prodSpu: "",
    prodStatus: null,
    prodType: null,
    tagId: null,
    unitId: null,
  };

  imageUrl.value = "";
};

//上传多图片
const fileList = ref<UploadUserFile[]>([]);
const attaImageUrl = ref("");
const dialogVisible = ref(false);
const handleRemove: UploadProps["onRemove"] = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles);
};
const handlePictureCardPreview: UploadProps["onPreview"] = (uploadFile) => {
  attaImageUrl.value = uploadFile.url!;
  dialogVisible.value = true;
};

//上传视频
const fileViewList = ref<UploadUserFile[]>([]);
const handleChange: UploadProps["onChange"] = (uploadFile, uploadFiles) => {
  fileViewList.value = fileViewList.value.slice(-3);
};

//确认添加商品附件
const submitAttaForm = async (formEl: FormInstance | undefined) => {
  //获取轮播图地址
  let attaImagesList = [];
  fileList.value.forEach((item) => {
    attaImagesList.push(item.response.data);
  });
  attaForm.value.attaImages = JSON.stringify(attaImagesList);

  //获取视频地址
  if (fileViewList.value.length <= 0) {
    ElMessage.error("请选择视频");
    return;
  }
  attaForm.value.attaVideo = fileViewList.value[0].response.data;

  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log("submit!");
      addProdAtta(attaForm.value).then((res) => {
        if (res.data.code == 200) {
          ElMessage.success("添加成功");
          attaFormVisible.value = false;
        } else {
          ElMessage.error(res.data.msg);
        }
      });
    } else {
      console.log("error submit!", fields);
    }
  });
};

const resetAttaForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
  attaFormVisible.value = false;
};
//显示添加商品附件对话框
const onAddAtta = (row: any) => {
  console.log("onAddProd");
  //清空轮播图
  fileList.value = [];
  //清空视频
  fileViewList.value = [];
  //清空表单
  attaForm.value = {
    attaImages: "",
    attaVideo: "",
    downFlag: null,
    downTime: null,
    prodId: null,
    upFlag: null,
    upTime: null,
  };

  attaForm.value.prodId = row.prodId;
  attaFormVisible.value = true;
};

//多选
const multipleSelection = ref<any[]>([]);
const handleSelectionChange = (val: any[]) => {
  multipleSelection.value = val;
};

//批量删除
const onDeleteBatch = () => {
  let num = multipleSelection.value;
  if (num == null || num.length < 0) {
    ElMessage.warning("请选择要删除的数据");
    return;
  }

  let ids = [];
  num.forEach((item) => {
    ids.push(item.prodId);
  });

  console.log("onDeleteBatch", ids);

  ElMessageBox.confirm("删除之后无法恢复，您确认要删除吗?", "警告", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then((res) => {
      deleteBatch(ids).then((res) => {
        if (res.data.code == 200) {
          ElMessage({
            type: "success",
            message: "删除成功",
          });
          loadProdList();
        }
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消删除",
      });
    });
};

//单删
const onDeleteProd = (row: any) => {
  console.log("onDeleteProd", row);

  ElMessageBox.confirm("删除之后无法恢复，您确认要删除吗?", "警告", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then((res) => {
      deleteProd(row.prodId).then((res) => {
        if (res.data.code == 200) {
          ElMessage({
            type: "success",
            message: "删除成功",
          });
          loadProdList();
        } else {
          ElMessage.error(res.data.msg);
        }
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消删除",
      });
    });
};

const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`);
  searchForm.value.pageSize = val;
  loadProdList();
};
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`);
  searchForm.value.pageNum = val;
  loadProdList();
};

const loadProdList = () => {
  getProdList(searchForm.value).then((res) => {
    if (res.data.code == 200) {
      tableData.value = res.data.data.records;
      total.value = res.data.data.total;
    }
  });
};

onMounted(() => {
  loadProdList();
  //分类列表数据
  getTypeInfo().then((res) => {
    if (res.data.code == 200) {
      typeList.value = res.data.data;
    }
  });
  //获取商品种类列表
  getDictList(1).then((res) => {
    if (res.data.code == 200) {
      kindList.value = res.data.data;
    }
  });
  //获取品牌列表
  getBrandList({ pageNum: 1, pageSize: 99999 }).then((res) => {
    if (res.data.code == 200) {
      brandList.value = res.data.data.records;
    }
  });
  //获取商品单位列表
  getDictList(2).then((res) => {
    if (res.data.code == 200) {
      unitList.value = res.data.data;
    }
  });
  //获取商品标签列表
  getDictList(3).then((res) => {
    if (res.data.code == 200) {
      tagList.value = res.data.data;
    }
  });
});
</script>
<!-- 分页样式 -->
<style scoped>
.demo-pagination-block + .demo-pagination-block {
  margin-top: 10px;
}
.demo-pagination-block .demonstration {
  margin-bottom: 16px;
}
</style>
<!-- 条件搜索样式 -->
<style>
.demo-form-inline .el-input {
  --el-input-width: 220px;
}

.demo-form-inline .el-select {
  --el-select-width: 220px;
}
</style>
<!-- 上传图片 -->
<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
